package com.yyk.yykywd.mvvm.base

import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.yyk.yykywd.base.BaseActivity
import org.devio.takephoto.app.TakePhoto
import org.devio.takephoto.app.TakePhotoFragmentActivity
import org.devio.takephoto.app.TakePhotoImpl
import org.devio.takephoto.model.InvokeParam
import org.devio.takephoto.model.TContextWrap
import org.devio.takephoto.model.TResult
import org.devio.takephoto.permission.InvokeListener
import org.devio.takephoto.permission.PermissionManager
import org.devio.takephoto.permission.TakePhotoInvocationHandler

/**
 * 文件描述：
 * Created by guo on 2019-11-22.
 */
open abstract class BaseTakePhotoActivity : BaseActivity(), TakePhoto.TakeResultListener, InvokeListener {

    companion object{
        const val TAG = "BaseTakePhotoActivity"
    }

    private var takePhoto: TakePhoto? = null
    private var invokeParam: InvokeParam? = null

    override fun invoke(invokeParam: InvokeParam?): PermissionManager.TPermissionType {
        val type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam!!.method)
        if (PermissionManager.TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        getTakePhoto()?.onCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        getTakePhoto()?.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        getTakePhoto()?.onSaveInstanceState(outState)
        super.onSaveInstanceState(outState)
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    protected fun getTakePhoto(): TakePhoto? { //获得TakePhoto实例
        if (takePhoto == null) {
            takePhoto = TakePhotoInvocationHandler.of(this).bind(TakePhotoImpl(this, this)) as TakePhoto
        }
        return takePhoto
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //以下代码为处理Android6.0、7.0动态权限所需
        val type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)
    }

    override fun takeCancel() {
        Log.i(TAG, "操作被取消")
    }

    override fun takeFail(result: TResult?, msg: String?) {
        Log.i(TAG, "takeFail:$msg")
    }
}